package com.connection.second.wallpaper.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.connection.second.common.core.domain.AjaxResult;
import com.connection.second.wallpaper.domain.entity.PaperAlbum;
import com.connection.second.wallpaper.domain.entity.PaperWall;
import com.connection.second.wallpaper.domain.vo.PaperAlbumVo;
import com.connection.second.wallpaper.domain.vo.PaperWallVo;
import com.connection.second.wallpaper.mapper.PaperAlbumMapper;
import com.connection.second.wallpaper.mapper.PaperClassifyMapper;
import com.connection.second.wallpaper.mapper.PaperWallMapper;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.connection.second.wallpaper.mapper.PaperUserCollectionMapper;
import com.connection.second.wallpaper.domain.entity.PaperUserCollection;
import com.connection.second.wallpaper.service.IPaperUserCollectionService;
import org.springframework.transaction.annotation.Transactional;

import static com.connection.second.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 用户收藏Service业务层处理
 * 
 * @author FL
 * @date 2024-11-15
 */

@Service
public class PaperUserCollectionServiceImpl implements IPaperUserCollectionService 
{
    @Autowired
    private PaperUserCollectionMapper paperUserCollectionMapper;
    @Autowired
    private PaperWallMapper paperWallMapper;
    @Autowired
    private PaperAlbumMapper paperAlbumMapper;
    @Autowired
    private PaperClassifyMapper paperClassifyMapper;

    /**
     * 查询用户收藏
     * 
     * @param id 用户收藏主键
     * @return 用户收藏
     */
    @Override
    public PaperUserCollection selectPaperUserCollectionById(Long id)
    {
        return paperUserCollectionMapper.selectPaperUserCollectionById(id);
    }

    /**
     * 查询用户收藏列表
     * 
     * @param paperUserCollection 用户收藏
     * @return 用户收藏
     */
    @Override
    public List<PaperUserCollection> selectPaperUserCollectionList(PaperUserCollection paperUserCollection)
    {
        return paperUserCollectionMapper.selectPaperUserCollectionList(paperUserCollection);
    }

    /**
     * 用户收藏、取消收藏
     *
     * @param paperUserCollection 用户收藏信息
     * @return 操作结果
     */
    @Override
    @Transactional
    public AjaxResult userCollection(PaperUserCollection paperUserCollection) {
        // 参数校验
        if (paperUserCollection.getType() != 1) {
            return AjaxResult.error("不支持的操作类型");
        }

        // 查询壁纸是否存在
        PaperWall wall = paperWallMapper.selectPaperWallById(paperUserCollection.getCollectId());
        if (wall == null) {
            return AjaxResult.error("壁纸不存在");
        }

        // 构建查询条件
        PaperUserCollection existingCollection = new PaperUserCollection();
        existingCollection.setUserId(paperUserCollection.getUserId());
        existingCollection.setCollectId(paperUserCollection.getCollectId());
        existingCollection.setType(paperUserCollection.getType());
//        获取当前用户的收藏记录
        List<PaperUserCollection> collectionList = paperUserCollectionMapper.selectPaperUserCollectionList(existingCollection);
        // 根据状态执行相应操作
        long oldCollections = Optional.ofNullable(wall.getCollections()).orElse(0L);
        if (ObjectUtil.isNotEmpty(collectionList)) {// 数据库有记录，说明已收藏过
            existingCollection.setId(collectionList.get(0).getId());
            if(paperUserCollection.getStatus() == 0){
                wall.setCollections(oldCollections - 1); // 取消收藏
                existingCollection.setStatus(0);
            }else if(paperUserCollection.getStatus() == 1){
                // 更新壁纸的收藏数量
                wall.setCollections(oldCollections + 1);
                existingCollection.setStatus(1);
            }
            paperWallMapper.updatePaperWall(wall);
            paperUserCollectionMapper.updatePaperUserCollection(existingCollection);


        } else{ // 数据库没有记录，说明是第一次收藏
            // 插入新的收藏记录
            paperUserCollection.setStatus(1);
            paperUserCollectionMapper.insertPaperUserCollection(paperUserCollection);
            wall.setCollections(oldCollections + 1);
            paperWallMapper.updatePaperWall(wall);
        }
        return AjaxResult.success("收藏成功");

    }

    /**
     * 修改用户收藏
     *
     * @param paperUserCollection 用户收藏
     * @return 结果
     */
    @Override
    public int updatePaperUserCollection(PaperUserCollection paperUserCollection)
    {
        return paperUserCollectionMapper.updatePaperUserCollection(paperUserCollection);
    }

    /**
     * 批量删除用户收藏
     * 
     * @param ids 需要删除的用户收藏主键
     * @return 结果
     */
    @Override
    public int deletePaperUserCollectionByIds(Long[] ids)
    {
        return paperUserCollectionMapper.deletePaperUserCollectionByIds(ids);
    }

    /**
     * 删除用户收藏信息
     * 
     * @param id 用户收藏主键
     * @return 结果
     */
    @Override
    public int deletePaperUserCollectionById(Long id)
    {
        return paperUserCollectionMapper.deletePaperUserCollectionById(id);
    }


    @Override
    public List<PaperWallVo> selectPaperWallList(PaperUserCollection paperUserCollection) {
//        查询用户收藏的壁纸
        paperUserCollection.setStatus(1);
        List<PaperUserCollection> collections = paperUserCollectionMapper.selectPaperUserCollectionList(paperUserCollection);
        return convertCollectionsToWallVo(collections);
    }

    @Override
    public List<PaperAlbumVo> selectPaperAlbumList(PaperUserCollection paperUserCollection) {
        List<PaperUserCollection> collections = paperUserCollectionMapper.selectPaperUserCollectionList(paperUserCollection);
        return convertCollectionsToAlbumVo(collections);
    }


    // 通用方法，将PaperUserCollection转换为PaperWallVo列表
    private List<PaperWallVo> convertCollectionsToWallVo(List<PaperUserCollection> collections) {
        log.info("1:{}",collections);
        List<PaperWallVo> list = new ArrayList<>();
        Set<Long> addedCollectIds = new HashSet<>(); // 用于跟踪已添加的 collectId

        // 收集所有的 collectId
        List<Long> collectIds = collections.stream()
                .map(PaperUserCollection::getCollectId)
                .collect(Collectors.toList());

        // 批量查询 PaperWall 信息
        List<PaperWall> walls = new ArrayList<>();
        for (Long id : collectIds) {
            PaperWall wall = paperWallMapper.selectPaperWallById(id);
            if (!ObjectUtil.isNull(wall)) {
                walls.add(wall);
            }
        }

        // 将结果存储到一个 Map 中，处理重复键
        Map<Long, PaperWall> wallMap = walls.stream()
                .collect(Collectors.toMap(PaperWall::getId, wall -> wall, (existing, replacement) -> existing)); // 保留第一个
        for (PaperUserCollection collection : collections) {
            if (!addedCollectIds.contains(collection.getCollectId())) { // 检查是否已添加
                PaperWallVo vo = new PaperWallVo();
                PaperWall wall = wallMap.get(collection.getCollectId());

                if (wall != null) {
                    BeanUtils.copyProperties(wall, vo);
                    String className = (wall.getClassId() != null) ?
                            paperClassifyMapper.selectPaperClassifyById(wall.getClassId()).getName() : "未分类";
                    vo.setClassName(className);
                    list.add(vo);
                    addedCollectIds.add(collection.getCollectId()); // 记录已添加的 collectId
                }
            }
        }

        return list;
    }


    // 通用方法，将PaperUserCollection转换为PaperAlbumVo列表
    private List<PaperAlbumVo> convertCollectionsToAlbumVo(List<PaperUserCollection> collections) {
        List<PaperAlbumVo> list = new ArrayList<>();
        for (PaperUserCollection collection : collections) {
            PaperAlbumVo vo = new PaperAlbumVo();
            PaperAlbum album = paperAlbumMapper.selectPaperAlbumById(collection.getCollectId());
            BeanUtils.copyProperties(album, vo);
            String className = (album.getClassId() != null) ?
                paperClassifyMapper.selectPaperClassifyById(album.getClassId()).getName() : "未分类";
            vo.setClassName(className);
            list.add(vo);
        }
        return list;
    }

}
